import {Component, OnInit} from '@angular/core';
import {differenceInCalendarDays} from 'date-fns';
import {NzUploadFile} from 'ng-zorro-antd/upload';
import {NzMessageService} from 'ng-zorro-antd/message';
import {Subscription} from 'rxjs';
import {CustomerManageService} from '../../customer-manage.service';
import {ActivatedRoute} from '@angular/router';
import {PermissionService} from '../../../../service/permission.service';
import { CommonService } from '../../../../services-common/common.service';

interface Form {
  title: string; // 标题
  abstract: string; // 摘要
  insideTitle: string; // 内部标题
  messageType: number; // 消息类型
  // terminal: string; // 适用终端
  belong: string; // 所属业务
  sendTimeType: number; // 发送消息时间的类型
  setSendDateTime: any; // 消息发送时间
  loginStartTime: any, // 登录时间限制:start
  loginEndTime: any, // 登录时间限制:end
  url: string; // 链接
  params: string; // 链接参数
  expirationTime: any; // 过期时间
  imageUrl: string; // 图片
  previewUrl: string;
}

@Component({
  selector: 'app-send-emails',
  templateUrl: './send-emails.component.html',
  styleUrls: ['./send-emails.component.scss']
})
export class SendEmailsComponent implements OnInit {
  emailDataId = ''; // 当前数据id
  emailDataStatus = 999; // 当前数据id
  form: Form = new Proxy({
    title: '', // 标题
    abstract: '', // 摘要
    insideTitle: '', // 内部标题
    messageType: 0, // 消息类型
    // terminal: '', // 适用终端
    belong: '0', // 所属业务
    sendTimeType: 1, // 发送消息时间的类型 1 立即发送 2 定时发送
    setSendDateTime: null, // 消息发送时间
    loginStartTime: null, // 登录时间限制:start
    loginEndTime: null, // 登录时间限制:end
    url: '', // 链接
    params: '', // 链接参数
    expirationTime: null, // 过期时间
    imageUrl: '', // 图片
    previewUrl: '',
  }, {
    set(target, key, value, receiver) {
      if (key === 'sendTimeType') {
        receiver.setSendDateTime = null;
        receiver.loginStartTime = null;
        receiver.loginEndTime = null;
      }
      return Reflect.set(target, key, value, receiver);
    }
  });
  sendUserForm = new Proxy({
    userId: '', // 用户ID
    userTel: '', // 手机号
    userInitialStatus: 3, // 用户初始身份
    userReallyStatus: 3, // 用户实际身份
    startValueRegister: null, // 注册时间 开始
    endValueRegister: null, // 注册时间 结束
    startValueChecked: null, // 审核通过时间 开始
    endValueChecked: null, // 审核通过时间 结束
    countUser: 0, // 符合条件的用户数量
  }, {
    set(target, key, value, receiver) {
      if (key !== 'countUser') {
        receiver.countUser = 0;
      }
      return Reflect.set(target, key, value, receiver);
    }
  });
  imageList: any[] = []; // 图片
  previewImg = ''; // 图片预览
  imgModifyStatus = false; // 图片是否已修改
  belongOptions: any[] = []; // 所属业务
  disabled = false; // 界面是否禁止操作
  checkModal = { // 审核模态框
    visible: false,
    remark: '',
    loading: false,
  };
  saveLoading = false;
  // 注册时间 开始 不可选
  disabledStartDateRegister = (startValue: Date): boolean => {
    if (!startValue || !this.sendUserForm.endValueRegister) {
      return false;
    }
    // @ts-ignore
    return startValue.getTime() > new Date(this.sendUserForm.endValueRegister).getTime();
  };
  // 注册时间 结束 不可选
  disabledEndDateRegister = (endValue: Date): boolean => {
    if (!endValue || !this.sendUserForm.startValueRegister) {
      return false;
    }
    // @ts-ignore
    return endValue.getTime() <= new Date(this.sendUserForm.startValueRegister).getTime();
  };
  // 审核通过时间 开始 不可选
  disabledStartDateChecked = (startValue: Date): boolean => {
    if (!startValue || !this.sendUserForm.endValueChecked) {
      return false;
    }
    // @ts-ignore
    return startValue.getTime() > new Date(this.sendUserForm.endValueChecked).getTime();
  };
  // 审核通过时间 结束 不可选
  disabledEndDateChecked = (endValue: Date): boolean => {
    if (!endValue || !this.sendUserForm.startValueChecked) {
      return false;
    }
    // @ts-ignore
    return endValue.getTime() <= new Date(this.sendUserForm.startValueChecked).getTime();
  };
  // 文件类型校验
  beforeUpload = (file: NzUploadFile): boolean => {
    const acceptFileType = [
      'bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif',
      'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps',
    ];
    const fileName: any = file.name.split('.').pop();
    if (!acceptFileType.includes(fileName)) {
      this.nzMessageService.warning('暂不支持该文件类型');
      return false;
    }
    this.getBase64(file, img => {
      this.previewImg = img;
    });
    this.imgModifyStatus = true;
    this.imageList = [file];
    return false;
  };
  disabledDate = (current: Date) => {
    return differenceInCalendarDays(current, new Date()) < 0;
  };

  /**
   * 登录时间限制
   * ----------------------------------------------------------------
   */
  loginDisabledStartDate = (startValue: Date): boolean => {
    if (!startValue || !this.form.loginEndTime) {
      return false;
    }
    return new Date(startValue).getTime() > new Date(this.form.loginEndTime).getTime();
  };

  loginDisabledEndDate = (endValue: Date): boolean => {
    if (!endValue || !this.form.loginStartTime) {
      return false;
    }
    return new Date(endValue).getTime() <= new Date(this.form.loginStartTime).getTime();
  };

  // 适用终端
  applyTerminalOptions: Array<any> = [];
  applyTerminalSelected: Array<any> = [];
  
  // 映射Options
  mappingOptions: Array<any> = [];

  constructor(
    private nzMessageService: NzMessageService,
    public customerManageService: CustomerManageService,
    private activatedRoute: ActivatedRoute,
    public permission: PermissionService,
    private commonService: CommonService
  ) {
  }

  ngOnInit(): void {
    this.getDict();
    this.loadApplyTerminal();
    this.getMappingData();
    this.disabled = this.activatedRoute.snapshot.queryParams?.disabled === 'disabled';
    this.emailDataId = this.activatedRoute.snapshot.queryParams?.id;
    this.loadOldData(this.emailDataId);
  }

  // 查询适用终端options
  async loadApplyTerminal() {
    this.applyTerminalOptions = await this.commonService.getDictList('channel');
  }

  // 获取映射list
  async getMappingData() {
    let params = {
      page: 1,
      pageSize: 2000
    }
    const res: any = await this.commonService.getMappingData(params);
    if (res.code === 0) {
      this.mappingOptions = res.data.records || []
    }
  }

  // 加载详情
  loadOldData(id: string) {
    if (!id) {
      return;
    }
    this.customerManageService.httpPost(this.customerManageService.serviceUrl.emailDetail, {id}).then((res: any) => {
      if (res.code === 0) {
        this.form.insideTitle = res.data.insideTitle;
        this.form.messageType = res.data.type;
        // this.form.terminal = res.data.terminal;
        // this.applyTerminalSelected = res.data.terminal ? res.data.terminal.split(',') : [];
        this.form.belong = String(res.data.belongingBusiness);
        this.form.sendTimeType = res.data.sendType;
        this.form.setSendDateTime = res.data.sendType === 2 ? res.data.sendTime : '';
        this.form.loginStartTime = res.data.sendType === 3 ? res.data.sendTime : '';
        this.form.loginEndTime = res.data.sendType === 3 ? res.data.loginEndTime : '';
        this.form.title = res.data.title;
        this.form.abstract = res.data.abstracts;
        this.form.url = res.data.url;
        this.form.params = res.data.params || '';
        this.form.expirationTime = res.data.expirationTime;
        this.form.imageUrl = res.data.img;
        this.previewImg = res.data.img;
        this.sendUserForm.userId = res.data.userId;
        this.sendUserForm.userTel = res.data.phone;
        this.sendUserForm.countUser = res.data.userNumber;
        this.emailDataStatus = res.data.state;
        this.sendUserForm.userInitialStatus = res.data.temUserType;
        this.sendUserForm.userReallyStatus = res.data.userType;
        this.sendUserForm.startValueRegister = res.data.registerBeginTime;
        this.sendUserForm.endValueRegister = res.data.registerTime;
        this.sendUserForm.startValueChecked = res.data.approvalBeginTime;
        this.sendUserForm.endValueChecked = res.data.approvalTime;
      }
    });
  }

  // 获取字典
  getDict() {
    this.customerManageService.httpGet(this.customerManageService.serviceUrl.dict, {
      pageNum: 1,
      pageSize: 999,
      parentKey: 'business'
    }).then((res: any) => {
      if (res.code === 0) {
        this.belongOptions = res.data.list.records;
      }
    });
  }

  /*
  * file转base64*/
  private getBase64(img: any, callback: (img: string) => void): void {
    const reader = new FileReader();
    // @ts-ignore
    reader.addEventListener('load', () => callback(reader.result.toString()));
    reader.readAsDataURL(img);
  }

  async save() {
    if (!this.form.insideTitle) {
      this.nzMessageService.warning('请输入内部标题');
      return;
    }
    // if (!this.applyTerminalSelected.length) {
    //   this.nzMessageService.warning('请选择适用终端');
    //   return;
    // }
    if (this.form.sendTimeType === 2 && !this.form.setSendDateTime) {
      this.nzMessageService.warning('请选择定时发送时间');
      return;
    }
    // if (!this.form.url) {
    //   this.nzMessageService.warning('请输入链接');
    //   return;
    // }
    if (!this.form.expirationTime) {
      this.nzMessageService.warning('请选择过期时间');
      return;
    }
    if (this.sendUserForm.userId && this.sendUserForm.userId.match(/[^0-9,]/g)) {
      this.nzMessageService.warning('用户id不能包含除数字和英文逗号之外的字符');
      return;
    }
    if (this.sendUserForm.userTel && this.sendUserForm.userTel.match(/[^0-9,]/g)) {
      this.nzMessageService.warning('用户手机号不能包含除数字和英文逗号之外的字符');
      return;
    }
    if (this.sendUserForm.userTel && !this.verifyTel(this.sendUserForm.userTel)) {
      this.nzMessageService.warning('手机号格式不正确');
      return;
    }
    const userNumber = await this.calcUsers();

    const params = {
      id: this.emailDataId,
      insideTitle: this.form.insideTitle, // 内部标题
      type: this.form.messageType, // 消息类型 0 活动优惠 1 系统消息
      // terminal: this.applyTerminalSelected.length ? this.applyTerminalSelected.join(',') : '', // 适用终端
      belongingBusiness: this.form.belong, // 所属业务(读取字典配置)
      sendType: this.form.sendTimeType, // 1审核后立即发生 2定时发送
      sendTime: this.form.sendTimeType === 2 ?
                this.customerManageService.formatTime(this.form.setSendDateTime, 'dateTime') :
                this.form.sendTimeType === 3 ?
                this.customerManageService.formatTime(this.form.loginStartTime, 'dateTime') :
                '', // 发送时间 | 登陆时间限制startTime
      loginEndTime: this.form.loginEndTime ? this.customerManageService.formatTime(this.form.loginEndTime, 'dateTime') : '', // 登录时间限制:end
      title: this.form.title, // 标题
      abstracts: this.form.abstract, // 摘要
      url: this.form.url || '', // 跳转链接
      params: this.form.params || '', // 链接参数
      expirationTime: this.customerManageService.formatTime(this.form.expirationTime, 'dateTime'), // 过期时间
      img: '', // 图片
      state: this.emailDataId ? 0 : '', // 0草稿 1待自动发送 2已发送 3已撤回 4已取消 5待审核 6审核不通过
      userId: this.sendUserForm.userId,
      phone: this.sendUserForm.userTel,
      temUserType: this.sendUserForm.userInitialStatus, // 初始
      userType: this.sendUserForm.userReallyStatus, // 实际
      registerBeginTime: this.customerManageService.formatTime(this.sendUserForm.startValueRegister, 'dateTime'), // 注册开始时间
      registerTime: this.customerManageService.formatTime(this.sendUserForm.endValueRegister, 'dateTime'), // 注册结束时间
      approvalBeginTime: this.customerManageService.formatTime(this.sendUserForm.startValueChecked, 'dateTime'), // 审核通过开始时间
      approvalTime: this.customerManageService.formatTime(this.sendUserForm.endValueChecked, 'dateTime'), // 审核通过结束时间
      userNumber
    };
    if (this.imgModifyStatus) {
      this.saveLoading = true;
      this.form.imageUrl = await this.fileUpload(this.imageList[0]) as string;
      this.saveLoading = false;
      params.img = this.form.imageUrl;
    } else if (!this.imgModifyStatus && this.form.imageUrl) {
      params.img = this.form.imageUrl;
    }
    if (!this.form.title && !this.form.abstract && !this.form.imageUrl) {
      this.nzMessageService.warning('标题、摘要、图片请至少填写一项');
      return;
    }
    this.saveLoading = true;
    const url = this.emailDataId ? this.customerManageService.serviceUrl.editEmail : this.customerManageService.serviceUrl.sendEmail;
    this.customerManageService.httpPost(url, params).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        window.history.go(-1);
      } else {
        this.nzMessageService.error(res.message);
      }
    }).catch((err) => {
      this.nzMessageService.error(err.message);
    }).finally(() => {
      this.saveLoading = false;
    });
  }

  // 文件上传
  fileUpload(file: any) {
    return new Promise((resolve, reject) => {
      if (!file) {
        return resolve('');
      }
      const fileData = new FormData();
      fileData.append('file', file);
      fileData.append('name', (+new Date()).toString());
      this.customerManageService.httpPost(this.customerManageService.serviceUrl.fileUpload, fileData).then((res: any) => {
        if (res.code === 0) {
          resolve(res.data);
        } else {
          this.nzMessageService.error('文件上传失败');
          resolve('');
        }
      }).catch(() => {
        this.nzMessageService.error('文件上传失败');
        resolve('');
      });
    });
  }

  // 计算人数
  calcUsers() {
    if (this.sendUserForm.userId && this.sendUserForm.userId.match(/[^0-9,]/g)) {
      this.nzMessageService.warning('用户id不能包含除数字和英文逗号之外的字符');
      return;
    }
    if (this.sendUserForm.userTel && this.sendUserForm.userTel.match(/[^0-9,]/g)) {
      this.nzMessageService.warning('用户手机号不能包含除数字和英文逗号之外的字符');
      return;
    }
    if (this.sendUserForm.userTel && !this.verifyTel(this.sendUserForm.userTel)) {
      this.nzMessageService.warning('手机号格式不正确');
      return;
    }
    this.sendUserForm.countUser = 0;
    return this.customerManageService.httpPost(this.customerManageService.serviceUrl.calcUser, {
      userId: this.sendUserForm.userId, // 用户ID
      phone: this.sendUserForm.userTel, // 手机号
      temUserType: this.sendUserForm.userInitialStatus, // 用户初始身份 2是B端 1C端 不限为空
      userType: this.sendUserForm.userReallyStatus, // 用户实际身份 2是B端 1C端 不限为空
      regBeginTime: this.customerManageService.formatTime(this.sendUserForm.startValueRegister, 'dateTime'), // 注册开始时间
      regEndTime: this.customerManageService.formatTime(this.sendUserForm.endValueRegister, 'dateTime'), // 注册结束时间
      auditBeginTime: this.customerManageService.formatTime(this.sendUserForm.startValueChecked, 'dateTime'), // 审核通过开始时间
      auditEngTime: this.customerManageService.formatTime(this.sendUserForm.endValueChecked, 'dateTime'), // 审核通过结束时间
    }).then((res: any) => {
      if (res.code === 0) {
        this.sendUserForm.countUser = res.data;
        
        if (!res.data) {
          this.nzMessageService.success('计算完成，但符合条件的用户数量为0。');
        }
        return res.data;
      } else {
        this.nzMessageService.error(res.message);
      }
    });
  }

  // 末尾添加逗号
  addComma(ref: any, key: string) {
    if (ref[key] && !ref[key].match(/,$/)) {
      ref[key] += ',';
    }
  }

  // 验证手机号
  verifyTel(value: string) {
    let result = true;
    if (!value.match(',') && !(/^[1][3456789][0-9]{9}$/).test(value)) {
      result = false;
    }
    value.split(',').forEach(item => {
      if (item !== ',' && !(/^[1][3456789][0-9]{9}$/).test(item)) {
        result = false;
      }
    });
    return result;
  }

  // 提交审核
  submitCheck() {
    this.customerManageService.httpPost(this.customerManageService.serviceUrl.emailCheck, {
      id: this.emailDataId,
      state: 5,
      auditDesc: ''
    }).then((res: any) => {
      if (res.code === 0) {
        this.loadOldData(this.emailDataId);
        this.nzMessageService.success('操作成功');
      } else {
        this.nzMessageService.error(res.message);
      }
    });
  }

  // 显示审核模态框
  checkModalShow() {
    this.checkModal.visible = true;
  }

  // 隐藏审核模态框
  checkModalHide() {
    this.checkModal = {
      visible: false,
      remark: '',
      loading: false,
    };
  }

  // 审核-拒绝
  checkReject() {
    if (!this.checkModal.remark) {
      this.nzMessageService.warning('拒绝时请输入审核意见');
      return;
    }
    this.checkModal.loading = true;
    this.customerManageService.httpPost(this.customerManageService.serviceUrl.emailCheck, {
      id: this.emailDataId,
      state: 6,
      auditDesc: this.checkModal.remark
    }).then((res: any) => {
      if (res.code === 0) {
        this.loadOldData(this.emailDataId);
        this.nzMessageService.success('操作成功');
        this.checkModalHide();
      } else {
        this.nzMessageService.error(res.message);
        this.checkModal.loading = false;
      }
    }).finally(() => {
      this.checkModal.loading = false;
    });
  }

  // 审核-通过
  checkResolve() {
    this.checkModal.loading = true;
    this.customerManageService.httpPost(this.customerManageService.serviceUrl.emailCheck, {
      id: this.emailDataId,
      state: 1,
      auditDesc: ''
    }).then((res: any) => {
      if (res.code === 0) {
        this.loadOldData(this.emailDataId);
        this.nzMessageService.success('操作成功');
        this.checkModalHide();
      } else {
        this.nzMessageService.error(res.message);
        this.checkModal.loading = false;
      }
    }).finally(() => {
      this.checkModal.loading = false;
    });
  }

  // 映射链接备注Filter
  remarkFilter(key: any) {
    let tempObj: any = this.mappingOptions.find((item: any) => {
      return item?.key === key;
    })
    return tempObj?.remarks || '';
  }
}
